# Setup environment ----
library(parallel)
library(data.table)
library(randomForest)
source("R/functions.R")
RNGkind("L'Ecuyer-CMRG")
results_path <- "results/replication/"
load(paste0(results_path, "house_analysis_data.RData"))
load(paste0(results_path, "senate_analysis_data.RData"))

# Senate Random Forests ----
set.seed(520391846)
senate_rf_model <- randomForest(x = sen_X_rf, y = sen_y[, 1], ntree = 1e5)
senate_rf_data <- data.table(
  dem_spend_adv = sen_X[, "dem_spend_adv"],
  d_dem_spend_adv = ((
    predict(senate_rf_model, Xp1S) -
      predict(senate_rf_model, Xm1S)) /
      (2 * dxS)),
  incl = sen_X[, "bottom_tail"] + sen_X[, "top_tail"] == 0)
cv_rf_sen <- cv_rf(sen_folds, sen_X_rf, sen_y, ntree = 1e5)
save(senate_rf_model, cv_rf_sen, senate_rf_data,
  file = paste0(results_path, "senate_rf.RData"))

# House Random Forests ----
set.seed(951358422)
house_rf_model <- randomForest(x = hou_X_rf, y = hou_y[, 1], ntree = 1000)
house_rf_data <- data.table(
  dem_spend_adv = hou_X[, "dem_spend_adv"],
  d_dem_spend_adv = ((
    predict(house_rf_model, Xp1H) -
      predict(house_rf_model, Xm1H)) /
      (2 * dxH)),
  incl = hou_X[, "bottom_tail"] + hou_X[, "top_tail"] == 0)
cv_rf_hou <- cv_rf(hou_folds, hou_X, hou_y, ntree = 1000)
save(house_rf_model, cv_rf_hou, house_rf_data,
  file = paste0(results_path, "house_rf.RData"))